package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import constants.StringConstants;

import DAO.DietDAO;
import DTO.DietDTO;

/**
 * Servlet implementation class DietServlet
 */
public class DietServlet extends HttpServlet {
	final static private String DISH_SERVLET = "DietServlet";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DietServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			DietDAO dao = new DietDAO();
			ArrayList<DietDTO> list = dao.select();

			request.setAttribute("DIETLIST", list);
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/diet.jsp");
			rd.forward(request, response);
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			request.setCharacterEncoding("UTF-8");
			String action = request.getParameter("action");
			if (action.equals(StringConstants.ADD)) {
				String name = request.getParameter("name");
				DietDTO diet = new DietDTO(0, name);
				DietDAO dao = new DietDAO();
				dao.add(diet);

				response.sendRedirect(DISH_SERVLET);
			} else if (action.equals(StringConstants.EDIT)) {
				int id = Integer.parseInt(request.getParameter("id"));
				String name = request.getParameter("name");
				DietDTO diet = new DietDTO(id, name);
				DietDAO dao = new DietDAO();
				dao.update(diet);

				response.sendRedirect(DISH_SERVLET);
			} else if (action.equals(StringConstants.DELETE)) {
				int id = Integer.parseInt(request.getParameter("id"));
				DietDAO dao = new DietDAO();
				dao.delete(id);

				response.sendRedirect(DISH_SERVLET);
			}
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}

	}

}
